import axios from 'axios';
import proxy from '../config/host';
import util from '@/libs/util';
import { MessagePlugin } from 'tdesign-vue';
import router from '@/router';
import store from '@/store';
import { TOKEN_NAME } from '@/config/global';

const env = import.meta.env.MODE || 'development';

const API_HOST = env === 'mock' ? '/' : proxy[env].API; // 如果是mock模式 就不配置host 会走本地Mock拦截

// 显示错误
function errorLog (err) {
  if (err.message) {
    MessagePlugin.error(`${err.message}`)
  }
}

const CODE = {
  LOGIN_TIMEOUT: 1000,
  REQUEST_SUCCESS: 1,
  REQUEST_FOBID: 1001,
};

const instance = axios.create({
  baseURL: API_HOST,
  timeout: 60000,
  withCredentials: false,
});

// axios的retry ts类型有问题
instance.interceptors.retry = 3;

instance.interceptors.request.use((config) => {
  config.headers = {
    'access_token': util.cookies.get(TOKEN_NAME),
    'content-type': config.contentType || 'application/x-www-form-urlencoded'
  }
  return config
});

instance.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      const { data, config } = response;
      if (data.retcode === undefined || data.retcode === null || data.retcode === CODE.REQUEST_SUCCESS) {
        return data;
      }
      // return response;
      let error = {
        message: '',
      }
      switch (data.retcode) {
        case -1: error.message = data.retmsg ? data.retcode + data.retmsg : '系统繁忙-'; break;
        case 0: error.message = data.retmsg ? data.retcode + data.retmsg : '无效请求'; break;
        case 4001 : error.message = data.retmsg ? data.retcode + data.retmsg : '无信息'; break;
        case 4002: error.message = data.retmsg ? data.retcode + data.retmsg : '缺少参数'; break;
        case 4003: error.message = data.retmsg ? data.retcode + data.retmsg : '参数有误'; break;
        case 4004: error.message = data.retmsg ? data.retcode + data.retmsg : '参数重复'; break;
        case 4055:
          router.replace(`/reset-pwd`)
          return data;
          break;
        case 4066: error.message = data.retmsg ? data.retcode + data.retmsg : '账号不存在';
          store.commit('user/removeToken')
          store.commit('user/removeUserName')
          router.push(`/login`)
          break;
        case 4077: error.message = data.retmsg ? data.retcode + data.retmsg : '身份令牌已失效或已过期';
          store.commit('user/removeToken')
          store.commit('user/removeUserName')
          router.push(`/login`)
          break;
        case 4088: error.message = data.retmsg ? data.retcode + data.retmsg : '没有权限或黑名单'; break;
        case 4099: error.message = data.retmsg ? data.retcode + data.retmsg : '未知错误'; break;
        case 500: error.message = data.retmsg ? data.retcode + data.retmsg : '服务器内部错误'; break;
        default: break;
      }
      if (!config.hideError) {
        errorLog(error);
      }
      return Promise.reject(data);
    }
  },
  (err) => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400: err.message = '请求错误'; break;
        case 401: err.message = '未授权，请登录';
          router.push(`/login`)
          break;
        case 403: err.message = '拒绝访问'; break;
        case 404: err.message = `请求地址出错: ${err.response.config.url}`; break;
        case 408: err.message = '请求超时'; break;
        case 500: err.message = err.response.data.msg ? err.response.data.msg : '服务器内部错误'; break;
        case 501: err.message = '服务未实现'; break;
        case 502: err.message = '网关错误'; break;
        case 503: err.message = '服务不可用'; break;
        case 504: err.message = '网关超时'; break;
        case 505: err.message = 'HTTP版本不受支持'; break;
        default: break;
      }
    }
    errorLog(err);

    const { config } = err;

    if (!config || !config.retry) return Promise.reject(err);

    config.retryCount = config.retryCount || 0;

    if (config.retryCount >= config.retry) {
      return Promise.reject(err);
    }

    config.retryCount += 1;

    const backoff = new Promise((resolve) => {
      setTimeout(() => {
        resolve({});
      }, config.retryDelay || 1);
    });

    return backoff.then(() => instance(config));
  },
);

export default instance;
